using FytSoa.Application.Crm.Param;
using FytSoa.Application.Erp;
using FytSoa.Common.Enum;
using FytSoa.Domain.Crm;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Masuit.Tools.Reflection;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Crm;

/// <summary>
/// 项目-回款服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v7")]
public class CrmPaymentService : IApplicationService 
{
    private readonly SugarRepository<CrmPayment> _thisRepository;
    private readonly ErpFlowUseService _flowUseService;
    private readonly CrmOperateLogService _operateLogService;
    public CrmPaymentService(SugarRepository<CrmPayment> thisRepository
        ,ErpFlowUseService flowUseService
        ,CrmOperateLogService operateLogService)
    {
        _thisRepository = thisRepository;
        _flowUseService = flowUseService;
        _operateLogService = operateLogService;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<CrmPaymentDto>> GetPagesAsync(CrmPaymentSearchParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Number.Contains(param.Key))
            .WhereIF(param.Id!=0,m=>m.CustomerId==param.Id)
            .WhereIF(param.ContractId!=0,m=>m.ContractId==param.ContractId)
            .Includes(m=>m.Customer)
            .Includes(m=>m.Contract)
            .Includes(m=>m.Employee)
            .Includes(m=>m.TypeCode)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<CrmPaymentDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<CrmPaymentDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.Customer)
            .Includes(m=>m.Contract)
            .Includes(m=>m.TypeCode)
            .Includes(m=>m.Employee)
            .FirstAsync(m=>m.Id==id);
        var result=model.Adapt<CrmPaymentDto>();
        result.Flow = await _flowUseService.GetFlowAsync(model.Id);
        return result;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(CrmPaymentDto model)
    {
        var toDay = await _thisRepository.CountAsync(m=>SqlFunc.DateIsSame(m.CreateTime,DateTime.Now));
        model.Number = "HK".ResNumber(toDay);
        var paymentId= await _thisRepository.InsertReturnSnowflakeIdAsync(model.Adapt<CrmPayment>());
        if (model.FlowId!=0)
        {
            await _flowUseService.AddAsync(new ErpFlowUseDto()
            {
                FlowId=model.FlowId,
                UseId=paymentId,
                Type = FlowTypeEnum.PayMent,
            });
        }
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = paymentId,
            Type = (int)OaOperateEnum.Payment,
            Remark = "创建了回款信息"
        });
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyAsync(CrmPaymentDto model)
    {
        if (model.Status==CrmAuditEnum.NotReviewed)
        {
            await _flowUseService.ModifyAsync(new ErpFlowUseDto()
            {
                FlowId = model.FlowId,
                UseId = model.Id,
                Type = FlowTypeEnum.PayMent,
            });
        }
        await _thisRepository.UpdateAsync(model.Adapt<CrmPayment>());
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = model.Id,
            Type = (int)OaOperateEnum.Payment,
            Remark = "修改了回款信息"
        });
    }
    
    /// <summary>
    /// 修改状态
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyStatusAsync(CrmContractStatusParam model)
    {
        await _thisRepository.UpdateAsync(m=>new CrmPayment()
        {
            Status = model.Status
        },m=>model.Id.Contains(m.Id));
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateIds = model.Id,
            Type = (int)OaOperateEnum.Payment,
            Remark = "变更了回款状态为："+model.Status.GetDescription()
        });
        if (model.Status==CrmAuditEnum.InReview)
        {
            foreach (var item in model.Id)
            {
                await _flowUseService.StartAuditAsync(item, FlowTypeEnum.PayMent);
            }
        }
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task DeleteAsync([FromBody] List<long> ids)
    {
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
        await _flowUseService.DeleteAsync(ids);
    }

}
